import Vue from 'vue'
import notification from 'ant-design-vue/es/notification'
import store from '@/store'
import axios from 'axios'
import VueAxios from 'vue-axios'
import { ACCESS_TOKEN } from '@/store/mutation-types.js'

// Vue.use(VueAxios, axios)
// Vue.prototype.$http = axios;
// axios.defaults.baseURL = 'http://127.0.0.1';
// axios.defaults.timeout = 5000;
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

// 创建 axios 实例
const service = axios.create({
	// baseURL: 'http://127.0.0.1:8132', // api base_url process.env.VUE_APP_API_BASE_URL
	baseURL: '/api',
	timeout: 6000 // 请求超时时间
})

const err = (error) => {
	if (error.response) {
		const data = error.response.data
		const token = Vue.ls.get(ACCESS_TOKEN)
		if (error.response.status === 403) {
			notification.error({
				message: 'Forbidden',
				description: data.message
			})
		}
		if (error.response.status === 401 && !(data.result && data.result.isLogin)) {
			notification.error({
				message: 'Unauthorized',
				description: 'Authorization verification failed'
			})
			if (token) {
				store.dispatch('Logout').then(() => {
					setTimeout(() => {
						// window.location.reload()
					}, 1500)
				})
			}
		}
	}
	return Promise.reject(error)
}

// request interceptor
service.interceptors.request.use(config => {
	
	const token = Vue.ls.get(ACCESS_TOKEN)
	
	if (token) {
		config.headers['Authorization'] = 'Bearer' + token // 让每个请求携带自定义 token 请根据实际情况自行修改
	}
	// window.console.log("config",config,token)
	return config
}, err)

// response interceptor
service.interceptors.response.use((response) => {
	
	// window.console.log("ACCESS_TOKEN",response.headers['access-token'])
	// if(response.headers && response.headers['access-token']){
	// 	Vue.ls.set(ACCESS_TOKEN, response.headers['access-token'])
	// }

	return response.data
}, err)

const installer = {
	vm: {},
	install(Vue) {
		Vue.use(VueAxios, service)
	}
}

export {
	installer as VueAxios,
	service as axios
}
